//
//  WmcCommonAddressTipView.swift
//  YPWatermarkCamera
//
//  Created by 周诗松 on 2022/8/5.
//

import AMapSearchKit
import UIKit

class WmcCommonAddressTipView: WmcBaseView {
    typealias Task = (_ cancel: Bool) -> Void

    // Internal

    private(set) var poi: AMapPOI?

    override var isHidden: Bool {
        didSet {
            if isHidden == false {
                WmcTrack.addBDAutoTrackEvent("bulletFrameExposure", params: ["name": "常用地址弹框"])

                if self.delayTask != nil {
                    self.cancel(self.delayTask)
                }

                delayTask = delay(3) { [weak self] in
                    guard let weakSelf = self else { return }
                    weakSelf.isHidden = true
                }
            }
        }
    }

    func updateModel(poi: AMapPOI) {
        isHidden = false
        addressLabel.text = poi.name
        self.poi = poi
    }

    func dismiss() {
        isHidden = true
        cancel(delayTask)
    }

    override func makeUI() {
        layer.shadowColor = UIColor.wmc_grayH13_ACAEAF.cgColor
        layer.shadowOpacity = 1.0
        layer.shadowOffset = CGSize(width: 0, height: 0)
        layer.shadowRadius = 4
        layer.cornerRadius = 8

        addSubview(addressLabel)
        addSubview(descLabel)
        addSubview(setBtn)

        addressLabel.snp.makeConstraints { make in
            make.left.equalTo(12)
            make.top.equalTo(15)
            make.height.equalTo(24)
            make.right.equalTo(setBtn.snp.left).offset(-12)
        }

        descLabel.snp.makeConstraints { make in
            make.left.equalTo(12)
            make.top.equalTo(addressLabel.snp.bottom).offset(4)
            make.height.equalTo(18)
            make.right.equalTo(setBtn.snp.left).offset(-12)
        }

        setBtn.snp.makeConstraints { make in
            make.width.equalTo(70)
            make.height.equalTo(32)
            make.right.equalTo(-12)
            make.centerY.equalToSuperview()
        }
    }

    override func bindViewAction() {
        setBtn.yp.addEvent { [weak self] _ in
            guard let weakSelf = self else { return }
            weakSelf.isHidden = true
            if let poi = weakSelf.poi {
                WmcCommonlyAddressDBManager.insert(model: poi) { isSuccess in
                    if isSuccess {
                        WmcLocationManager.setCommonlyAddress(poi: poi)
                        WmcHudManager.toast("已设为常用地点")
                    }
                }
            }
        }
    }

    // Private

    private lazy var addressLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 16, weight: .semibold)
        label.textColor = .wmc_grayH2_323233
        return label
    }()

    private lazy var descLabel: UILabel = {
        let label = UILabel()
        label.text = "在附近时自动选择，无需手动更改"
        label.font = 14.wmc_font
        label.textColor = .wmc_grayH8_8A8A99
        return label
    }()

    private lazy var setBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("设为常用", for: .normal)
        btn.setTitleColor(.wmc_white_FFFFFF, for: .normal)
        btn.titleLabel?.font = 14.wmc_font
        btn.setBackgroundImage(UIColor.wmc_mainTheme.yp.uiImage, for: .normal)
        btn.layer.cornerRadius = 4.0
        btn.layer.masksToBounds = true
        return btn
    }()

    private var delayTask: Task?

    @discardableResult
    private func delay(_ time: TimeInterval, task: @escaping () -> Void) -> Task? {
        func dispatch_later(_ block: @escaping () -> Void) {
            DispatchQueue.main.asyncAfter(
                deadline: DispatchTime.now() + Double(Int64(time * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC),
                execute: block)
        }

        var closure: (() -> Void)? = task
        var result: Task?
        let delayedClosure: Task = { cancel in
            if let internalClosure = closure {
                if (cancel == false) {
                    DispatchQueue.main.async(execute: internalClosure)
                }
            }
            closure = nil
            result = nil
        }
        result = delayedClosure
        dispatch_later {
            if let delayedClosure = result {
                delayedClosure(false)
            }
        }

        return result
    }

    private func cancel(_ task: Task?) {
        task?(true)
    }
}
